package cn.ac.aircas.framework.web.service;

import javax.annotation.Resource;

import cn.ac.aircas.common.constant.HttpStatus;
import cn.ac.aircas.common.exception.user.*;
import cn.ac.aircas.common.utils.http.HttpUtils;
import cn.ac.aircas.framework.config.OAuth2Config;
import cn.ac.aircas.common.utils.*;
import cn.ac.aircas.framework.config.SocialUtils;
import cn.ac.aircas.framework.config.properties.SocialLoginConfigProperties;
import cn.ac.aircas.system.domain.SysConfig;
import cn.ac.aircas.system.mapper.SysConfigMapper;
import cn.ac.aircas.system.mapper.SysRoleRegionMapper;
import com.alibaba.fastjson2.JSONObject;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthGithubRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.request.AuthWeiboRequest;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import cn.ac.aircas.common.constant.CacheConstants;
import cn.ac.aircas.common.constant.Constants;
import cn.ac.aircas.common.constant.UserConstants;
import cn.ac.aircas.common.core.domain.entity.SysUser;
import cn.ac.aircas.common.core.domain.model.LoginUser;
import cn.ac.aircas.common.core.redis.RedisCache;
import cn.ac.aircas.common.exception.ServiceException;
import cn.ac.aircas.common.utils.ip.IpUtils;
import cn.ac.aircas.framework.manager.AsyncManager;
import cn.ac.aircas.framework.manager.factory.AsyncFactory;
import cn.ac.aircas.framework.security.context.AuthenticationContextHolder;
import cn.ac.aircas.system.service.ISysConfigService;
import cn.ac.aircas.system.service.ISysUserService;

import java.io.IOException;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.util.*;

/**
 * 登录校验方法
 *
 * @author defected
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    OAuth2Config oAuth2Config;

    @Autowired
    private GiteeHttpClient giteeHttpClient;

    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Autowired
    private SysRoleRegionMapper sysRoleRegionMapper;


    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid, Integer regionId) {
        try {
            password = AesUtils.decrypt(password);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 验证码校验
//        validateCaptcha(username, code, uuid);

        // 登录前置校验
        loginPreCheck(username, password);

        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        // 城市校验
        validateCity(username, regionId);

        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            validateCaptchaCode(username, code, captcha);
        }
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @param delete   是否删除缓存
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid, boolean delete) {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);

        if (delete) {
            redisCache.deleteObject(verifyKey);
        }

        validateCaptchaCode(username, code, captcha);
    }

    public void validateCaptchaCode(String username, String captcha, String code) {
        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
    }

    /**
     * 城市校验
     */
    public void validateCity(String username, Integer regionId) {
        Integer exist = sysRoleRegionMapper.checkRegionByUsername(username, regionId);
        if (exist == null || exist == 0) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new RegionException();
        }
    }

    /**
     * 登录前置校验
     *
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        // if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
        //         || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
        //     AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
        //     throw new UserPasswordNotMatchException();
        // }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    public String loginByOtherSource(String code, String source, String uuid) throws IOException {
        SocialLoginConfigProperties loginConfigProperties = oAuth2Config.getType().get(source.toLowerCase(Locale.ROOT));
        // 先到数据库查询这个人曾经有没有登录过，没有就注册
        // 创建授权request
        SysUser sysUser = new SysUser();

        // Step2：通过Authorization Code获取Access Token
        String url = "https://gitee.com/oauth/token?grant_type=authorization_code" +
                "&client_id=" + loginConfigProperties.getClientId() +
                "&client_secret=" + loginConfigProperties.getClientSecret() +
                "&code=" + code +
                "&redirect_uri=" + loginConfigProperties.getRedirectUri();

        JSONObject accessToken = GiteeHttpClient.getAccessToken(url);

        if (accessToken == null || accessToken.containsKey("error")) {
            return null;
        } else {
            // Step3: 获取用户信息
            url = "https://gitee.com/api/v5/user?access_token=" + accessToken.get("access_token");
            JSONObject jsonObject = GiteeHttpClient.getUserInfo(url);
            /**
             * 获取到用户信息之后，就该写你自己的业务逻辑了
             */
            sysUser.setUserName(jsonObject.getString("login"));
            sysUser.setNickName(jsonObject.getString("name"));
            sysUser.setUid(jsonObject.getLong("id"));
            sysUser.setAvatar(jsonObject.getString("avatar_url"));
            sysUser.setRemark(jsonObject.getString("remark"));

            List<SysUser> sysUsers = userService.selectUserListNoDataScope(sysUser);
            if (sysUsers.isEmpty()) {
                // 相当于注册
                this.addOrUpdateUser(sysUser);
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(sysUser.getUserName(), Constants.REGISTER,
                        MessageUtils.message("user.register.success")));
            } else {
                sysUser = sysUsers.get(0);
            }
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(sysUser.getUserName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
            // 注册成功或者是已经存在的用户
            LoginUser loginUser =
                    new LoginUser(sysUser.getUserId(), sysUser.getDeptId(), sysUser, permissionService.getMenuPermission(sysUser));
            recordLoginInfo(loginUser.getUserId());
            // 生成token
            return tokenService.createToken(loginUser);
        }

    }

    public void addOrUpdateUser(SysUser sysUser) {
        if (userService.checkUserNameUnique(sysUser)) {
            List<Long> ids = new ArrayList<>();
            ids.add(Long.parseLong(configService.selectConfigByKey("sys.user.initRoleId")));
            sysUser.setRoleIds(ids.toArray(new Long[0]));
            sysUser.setCreateBy("OAuth2");
            sysUser.setDeptId(Long.parseLong(configService.selectConfigByKey("sys.user.initDeptId")));
            ids.clear();
            ids.add(Long.parseLong(configService.selectConfigByKey("sys.user.initPostId")));
            sysUser.setPostIds(ids.toArray(new Long[0]));
            sysUser.setPassword(SecurityUtils.encryptPassword(configService.selectConfigByKey("sys.user.initPassword")));

            userService.insertUser(sysUser);
        }
    }

    public String loginByThirdPlatSource(String code, String source, String uuid) throws Exception {
        SocialLoginConfigProperties configProperties = oAuth2Config.getType().get(source);
        Map<String, String> param = new HashMap();
        param.put("grant_type", "authorization_code");
        param.put("client_id", configProperties.getClientId());
        param.put("client_secret", configProperties.getClientSecret());
        param.put("redirect_uri", configProperties.getRedirectUri());
        param.put("code", code);
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded");

        SysUser sysUser = new SysUser();
        HttpResponse response = HttpUtils.doPost("https://oauth-login.cloud.huawei.com", "/oauth2/v3/token", "post", headers, null, param);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SUCCESS) {
            String result = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(result);
            String idToken = jsonObject.getString("id_token");
            param.clear();
            param.put("id_token", idToken);
            response = HttpUtils.doPost("https://oauth-login.cloud.huawei.com", "/oauth2/v3/tokeninfo", "post", headers, null, param);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SUCCESS) {
                result = EntityUtils.toString(response.getEntity());
                jsonObject = JSONObject.parseObject(result);

                sysUser.setUserName(jsonObject.getString("nickname"));
                sysUser.setSource(source);
                List<SysUser> sysUsers = userService.selectUserListNoDataScope(sysUser);
                if (sysUsers.size() > 1) {
                    throw new ServiceException("第三方登录异常，账号重叠");
                } else if (sysUsers.isEmpty()) {
                    ;
                    // 相当于注册
                    sysUser.setNickName(jsonObject.getString("nickname") + "(" + jsonObject.getString("name") + ")");
                    sysUser.setAvatar(jsonObject.getString("picture"));
                    sysUser.setUid(jsonObject.getLong("aud"));
                    this.addOrUpdateUser(sysUser);
                } else {
                    sysUser = sysUsers.get(0);
                }
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(sysUser.getUserName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        // 注册成功或者是已经存在的用户
        LoginUser loginUser =
                new LoginUser(sysUser.getUserId(), sysUser.getDeptId(), sysUser, permissionService.getMenuPermission(sysUser));
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    public String loginByGitHubSource(String code, String source, String uuid) {
        SocialLoginConfigProperties loginConfigProperties = oAuth2Config.getType().get(source.toLowerCase(Locale.ROOT));
        // 先到数据库查询这个人曾经有没有登录过，没有就注册
        // 创建授权request
        AuthRequest authRequest = new AuthGithubRequest(AuthConfig.builder()
                .clientId(loginConfigProperties.getClientId())
                .clientSecret(loginConfigProperties.getClientSecret())
                .redirectUri(loginConfigProperties.getRedirectUri())
                .build());
        AuthResponse<AuthUser> login = authRequest.login(AuthCallback.builder().state(uuid).code(code).build());
        System.out.println(login);
        // 先查询数据库有没有该用户
        int resCode = login.getCode();
        if (resCode == 5000) {
            throw new ServiceException("GitHub连接超时，请稍后重试（或更换其他平台）", 4402);
        }
        AuthUser authUser = login.getData();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(authUser.getUsername());
        sysUser.setSource(authUser.getSource());
        List<SysUser> sysUsers = userService.selectUserListNoDataScope(sysUser);
        if (sysUsers.size() > 1) {
            throw new ServiceException("第三方登录异常，账号重叠");
        } else if (sysUsers.isEmpty()) {
            // 相当于注册
            sysUser.setNickName(authUser.getNickname() == null ? "aircas" : authUser.getNickname());
            sysUser.setUid(Long.valueOf(authUser.getUuid()));
            sysUser.setAvatar(authUser.getAvatar());
            sysUser.setEmail(authUser.getEmail());
            sysUser.setRemark(authUser.getRemark());
            this.addOrUpdateUser(sysUser);
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(sysUser.getUserName(), Constants.REGISTER,
                    MessageUtils.message("user.register.success")));
        } else {
            sysUser = sysUsers.get(0);
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(sysUser.getUserName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        // 注册成功或者是已经存在的用户
        LoginUser loginUser =
                new LoginUser(sysUser.getUserId(), sysUser.getDeptId(), sysUser, permissionService.getMenuPermission(sysUser));
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    public String loginByWeiboSource(String code, String source, String uuid) {
        SocialLoginConfigProperties loginConfigProperties = oAuth2Config.getType().get(source.toLowerCase(Locale.ROOT));
        // 先到数据库查询这个人曾经有没有登录过，没有就注册
        // 创建授权request
        AuthRequest authRequest = new AuthWeiboRequest(AuthConfig.builder()
                .clientId(loginConfigProperties.getClientId())
                .clientSecret(loginConfigProperties.getClientSecret())
                .redirectUri(loginConfigProperties.getRedirectUri())
                .build());
        AuthResponse<AuthUser> login = authRequest.login(AuthCallback.builder().state(uuid).code(code).build());
        System.out.println(login);
        // 先查询数据库有没有该用户
        int resCode = login.getCode();
        if (resCode == 5000) {
            throw new ServiceException("GitHub连接超时，请稍后重试（或更换其他平台）", 4402);
        }
        AuthUser authUser = login.getData();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(authUser.getUsername());
        sysUser.setSource(authUser.getSource());
        List<SysUser> sysUsers = userService.selectUserListNoDataScope(sysUser);
        if (sysUsers.size() > 1) {
            throw new ServiceException("第三方登录异常，账号重叠");
        } else if (sysUsers.isEmpty()) {
            // 相当于注册
            sysUser.setNickName(authUser.getNickname() == null ? "aircas" : authUser.getNickname());
            sysUser.setUid(Long.valueOf(authUser.getUuid()));
            sysUser.setAvatar(authUser.getAvatar());
            sysUser.setEmail(authUser.getEmail());
            sysUser.setRemark(authUser.getRemark());
            this.addOrUpdateUser(sysUser);
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(sysUser.getUserName(), Constants.REGISTER,
                    MessageUtils.message("user.register.success")));
        } else {
            sysUser = sysUsers.get(0);
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(sysUser.getUserName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        // 注册成功或者是已经存在的用户
        LoginUser loginUser =
                new LoginUser(sysUser.getUserId(), sysUser.getDeptId(), sysUser, permissionService.getMenuPermission(sysUser));
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }


    public String loginByThirdPlatformSource(String code, String source, String uuid) {
        // 先到数据库查询这个人曾经有没有登录过，没有就注册
        // 创建授权request
        AuthRequest authRequest = SocialUtils.getAuthRequest(source, oAuth2Config);
        AuthResponse<AuthUser> login = authRequest.login(AuthCallback.builder().state(uuid).code(code).build());
        System.out.println(login);
        // 先查询数据库有没有该用户
        int resCode = login.getCode();
        if (resCode == 5000) {
            throw new ServiceException("连接超时，请稍后重试（或更换其他平台）", 4402);
        }
        AuthUser authUser = login.getData();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(authUser.getUsername());
        sysUser.setSource(authUser.getSource());
        List<SysUser> sysUsers = userService.selectUserListNoDataScope(sysUser);
        if (sysUsers.size() > 1) {
            throw new ServiceException("第三方登录异常，账号重叠");
        } else if (sysUsers.isEmpty()) {
            // 相当于注册
            sysUser.setNickName(authUser.getNickname() == null ? "aircas" : authUser.getNickname());
            sysUser.setUid(Long.valueOf(authUser.getUuid()));
            sysUser.setAvatar(authUser.getAvatar());
            sysUser.setEmail(authUser.getEmail());
            sysUser.setRemark(authUser.getRemark());
            this.addOrUpdateUser(sysUser);
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(sysUser.getUserName(), Constants.REGISTER,
                    MessageUtils.message("user.register.success")));
        } else {
            sysUser = sysUsers.get(0);
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(sysUser.getUserName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        // 注册成功或者是已经存在的用户
        LoginUser loginUser =
                new LoginUser(sysUser.getUserId(), sysUser.getDeptId(), sysUser, permissionService.getMenuPermission(sysUser));
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    public boolean isPwdExpire(SysUser sysUser) {
        Date pwdTime = sysUser.getPwdTime();

        if (pwdTime == null) {
            return true;
        }

        LocalDate pwdDate = pwdTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 计算日期差异
        Period period = Period.between(pwdDate, currentDate);
        // 检查月份差异是否大于等于三个月
        SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique("sys.user.pass.interval");
        return period.toTotalMonths() >= Long.parseLong(sysConfig.getConfigValue());
    }
}